/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller.CoreServlet;

import Controller.CoreServlet.Ultility.SSCookie_Login;
import Model.BeanUltility.PopulateBean;
import Model.BeanUltility.ResultsetMapper;
import Model.DataUltility.Data_Access;
import Model.ObjectBean.RequestBean.*;
import Model.ObjectBean.ViewBean.*;
import Model.ObjectBean.ViewBean.PersonalInfo_FrDatabase;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Controller.CoreServlet.Ultility.*;
import Ultility.RandomCollection;
import Model.DataUltility.*;

/**
 *
 * @author chickencake1
 */
public class checkoutServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       String state=request.getParameter("state");
       if(state==null)
           state="notState";
       
               request.setCharacterEncoding("UTF-8");
            
        response.setContentType("text/html;charset=UTF-8");
        Data_Access access = new Data_Access();
        PrintWriter out = response.getWriter();
        String customer = request.getParameter("isNewCustomer");
        String change = request.getParameter("isChange");
        if(change==null)
            change="notchange";
         Checkout update = new Checkout();
        BeanCheckout checkout = new BeanCheckout();
        ShoppingCart cart = (ShoppingCart)request.getSession().getAttribute("shoppingcart");
       
       if(state.equals("firsttime"))
       {
           RequestDispatcher dispatcher=request.getRequestDispatcher("/WEB-INF/MainJSP/CheckoutPage.jsp");
           dispatcher.forward(request, response);
       }
       if(state.equals("member"))
       {
           double price=0;
           String temp=RandomCollection.ChacractersRandom();
           while(update.isConflict("bill","bill_id", temp))
               temp=RandomCollection.ChacractersRandom();
           String bill_id=temp;
           
           for(int i=0;i<cart.getItemsOrdered().size();i++)
           {
               String bill_detail_id="";
               ItemOrder order=(ItemOrder)cart.getItemsOrdered().get(i);
           String temp1=RandomCollection.ChacractersRandom();
           while(update.isConflict("bill_detail","bill_detail_id", temp1))
               temp1=RandomCollection.ChacractersRandom();
           bill_detail_id=temp1;
           String [] data={bill_detail_id,bill_id,order.getItem_ID()};
           access.insertInformation("bill_detail", data);
           
           
           
               update.product_Update("stock",order.getNumberItems(),"re_id",order.getItem_ID());
               price+=order.getTotalCost();
                       
           }

           PersonalInfo_FrDatabase info = (PersonalInfo_FrDatabase) request.getSession().getAttribute("perInfo");
           String [] data1 ={bill_id,"1",info.getId(),Double.toString(price),info.getPayment_style()};
           access.insertInformation("bill", data1);
           
          
           
            RequestDispatcher dispatcher =request.getRequestDispatcher("/WEB-INF/MainJSP/CheckoutPage.jsp");
            dispatcher.forward(request, response);
       }        
             
      if(customer.equals("old"))
      {

          
          UserAccount_FrClient clientInfo= new UserAccount_FrClient();
            
            LoginStatus status =new LoginStatus();  
            
            status.setStatus("false");
            
            PersonalInfo_FrDatabase perInfo = new PersonalInfo_FrDatabase(); 
            
            Data_Access accessDB = new Data_Access();

           
            request.getSession().setAttribute("status", status);
            request.getSession().setAttribute("perInfo", perInfo);
                      
            RequestDispatcher dispatcher =request.getRequestDispatcher("/WEB-INF/MainJSP/CheckoutPage.jsp");

      try{     
            
            
            // 1 : check by value

            PopulateBean.populateBeans(clientInfo,request);
            //Step2
            String []column={"id","passw"};
            String []data={clientInfo.getUsername(),clientInfo.getPassword()};
            ResultSet rs = accessDB.getInformation("login_account", column, data);
            
            //Step2
            String []column1={"id"};
            String []data1={clientInfo.getUsername()};
            ResultSet rs1 =accessDB.getInformation("personal_info",column1,data1);
            ResultsetMapper.mapperResultsettoObject(rs1,PersonalInfo_FrDatabase.class,perInfo);
            
            //Step 3
            rs.last();
            int count=rs.getRow();
            
            //
             // If login successfully , send session cookie to browser . 
             // It will be save in browser memory and lost when browser quit.
             //
            if(count==1)
            {

                status.setStatus("true"); 
                // add cookie for this user
                SSCookie_Login.add_ShortTime_Cookies(response,clientInfo.getUsername(),"logged");
                //SSCookie_Login.add_ShortTime_Cookies(response,"perInf",perInfo.getFirstname());
                SSCookie_Login.add_ShortTime_Cookies(response,"username",clientInfo.getUsername());
                SSCookie_Login.add_ShortTime_Cookies(response,"passw",clientInfo.getPassword());
           if(change.equals("true"))
          {
              String paystyle=request.getParameter("payment_style");
              if(paystyle==null)
                  paystyle="notstyle";
            if(!paystyle.equals("notstyle"))
            {
                if(request.getParameter("payment_style").equals("0"))
                {
                           perInfo.setPayment_style("0");
                }
                else{
                    perInfo.setPayment_style("1");
                }
            }
          }          

          /* double price=0;
           for(int i=0;i<cart.getItemsOrdered().size();i++)
           {
               ItemOrder order=(ItemOrder)cart.getItemsOrdered().get(i);
              
               update.product_Update("stock",order.getNumberItems(),"re_id",order.getItem_ID());
               price+=order.getTotalCost();
                       
           }*/
          //------------------------------------------------------------------

           double price=0;
           String temp=RandomCollection.ChacractersRandom();
           while(update.isConflict("bill","bill_id", temp))
               temp=RandomCollection.ChacractersRandom();
           String bill_id=temp;
           
           for(int i=0;i<cart.getItemsOrdered().size();i++)
           {
               String bill_detail_id="";
               ItemOrder order=(ItemOrder)cart.getItemsOrdered().get(i);
           String temp1=RandomCollection.ChacractersRandom();
           while(update.isConflict("bill_detail","bill_detail_id", temp1))
               temp1=RandomCollection.ChacractersRandom();
           bill_detail_id=temp1;
           String [] data3={bill_detail_id,bill_id,order.getItem_ID()};
           access.insertInformation("bill_detail", data3);
           
           
           
               update.product_Update("stock",order.getNumberItems(),"re_id",order.getItem_ID());
               price+=order.getTotalCost();
                       
           }

           PersonalInfo_FrDatabase info = (PersonalInfo_FrDatabase) request.getSession().getAttribute("perInfo");
           String [] data4 ={bill_id,"1",info.getId(),Double.toString(price),info.getPayment_style()};
           access.insertInformation("bill", data4);
           
           
           
          //------------------------------------------------------------------ 
           dispatcher.forward(request, response);
            }
            else
            {  
                status.setStatus("false");
                out.println("Sai");
                dispatcher.forward(request, response);

            }
            
        } catch (Exception ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
            dispatcher.forward(request, response);

        }
      }
      else
      {
           RequestDispatcher dispatcher =request.getRequestDispatcher("/WEB-INF/MainJSP/RegisterPage.jsp");
           dispatcher.forward(request, response);
      }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

 
}
